package com.moyu.oasys.file.controller;

import com.github.pagehelper.PageInfo;
import com.moyu.common.core.domain.Page;
import com.moyu.common.core.domain.R;
import com.moyu.oasys.file.entity.File;
import com.moyu.oasys.file.service.IFileService;
import io.minio.errors.*;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @Author 赵彦博
 * @Date 2024/12/5 10:15
 */
@RestController
@RequestMapping("/files")
public class FileController {

    private final IFileService fileService;

    public FileController(IFileService fileService) {
        this.fileService = fileService;
    }

    @GetMapping
    public R<Page<File>> listFile(@RequestParam(defaultValue = "1") int pageNumber, @RequestParam(defaultValue = "10") int pageSize, File file) {
        PageInfo<File> pageInfo = fileService.listByEntity(pageNumber, pageSize, file);
        return R.ok(Page.of(pageInfo.getList(), pageInfo.getTotal()));
    }

    @PostMapping
    public R<File> createFile(@RequestParam(required = false) MultipartFile multipartFile, @Validated({File.CreateFile.class, File.CreateFolder.class}) File file)
            throws IOException, ServerException, InsufficientDataException, NoSuchAlgorithmException, InternalException,
            InvalidResponseException, XmlParserException, InvalidKeyException, ErrorResponseException {
        return R.ok(fileService.create(multipartFile, file));
    }

    @GetMapping("{id}")
    public void downloadFile(@PathVariable Long id, HttpServletResponse response) throws IOException, ServerException, InsufficientDataException,
            NoSuchAlgorithmException, InternalException, InvalidResponseException, XmlParserException, InvalidKeyException, ErrorResponseException {
        fileService.getById(id, response);
    }

    @PutMapping
    public R<File> updateFile(@RequestBody @Validated({File.Update.class}) File file) {
        //todo 验证是否为自己的文件
        File updatedFile = fileService.update(file);
        return R.ok(updatedFile);
    }

    @DeleteMapping("{id}")
    public R deleteFile(@PathVariable Long id) throws IOException, InvalidResponseException, InvalidKeyException,
            NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InsufficientDataException, InternalException {
        fileService.deleteById(id);
        return R.ok();
    }

}
